<script setup>
import * as api from "@/api/v-msg-service/sms-manage/sms-account";

const emits = defineEmits([
  'query',
  'update:modelValue'
])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
})

const formData = ref({
  id: '',
  accessKey: '',//账户
  secretKey: '',//密码
  url: '',//url地址
  channelNameCode: '',//渠道名称
})

const saveBtnLoading = ref(false)
const formRef = ref()
const checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error('编码不能输入汉字!'));
    } else {
      callback();
    }
  }
  callback();
}

const rules = ref({
  accessKey: [
    { validator: checkData, trigger: 'change' },
    { required: true, message: "请输入AccessKey ID", trigger: "blur" }
  ],
  secretKey: [
    { validator: checkData, trigger: 'change' },
    { required: true, message: "请输入Access Key Secret", trigger: "blur" }
  ],
  channelNameCode: [{ required: true, message: "渠道名称不能为空", trigger: "blur" }],
})
const visible = computed(
    {
      get(){
        return props.modelValue
      },
      set(val){
        emits('update:modelValue',val)
      }
    }
)

const title = computed(
    () => {
      return props.rowData && props.rowData.id ? '编辑配置' : '新增配置'
    }
)
watch(
    props.rowData,
    (val) =>{
      if (val && val.id) Object.assign(formData.value,val)
    },
    {
      immediate: true,
    }
)
onMounted(()=>{
  init()
})
const init = () => {
  init_Cache()
}
const init_Cache = () => {

}
const sure = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      saveBtnLoading.value = true
      const { code } = await api.save(formData.value)
      saveBtnLoading.value = false
      if (code === 200){
        visible.value = false
        ElMessage({message: '保存成功', type: 'success',})
        emits('query')
      }
    }
  })
}
</script>

<template>
  <v-dialog v-model="visible" :loading="saveBtnLoading" :title="title" @sure="sure">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="180px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="短信渠道：" prop="channelNameCode">
            <v-select-dict v-model="formData.channelNameCode" type-code="SmsChannelCode" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="AccessKey ID：" prop="accessKey">
            <el-input v-model="formData.accessKey"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Access Key Secret：" prop="secretKey">
            <el-input v-model="formData.secretKey"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </v-dialog>
</template>

<style scoped lang="scss">
.el-select {
  width: 100%;
}
</style>